import {
  adList
} from "../../utils/adConfig.js";
import {
  requst_post_addPoint,
  requst_post_likePic,
} from '../../utils/api.js'
var t = require("../../utils/api"),
  app = getApp();
// 在页面中定义插屏广告
let interstitialAd = null
// 在页面中定义激励视频广告
let videoAd = null;
Page({
  data: {

    isLike: 0,
    id: 0,
    imageUrl: "",
    detail: "",
    relateposts: [],
    detailAds: "",
    current: 0,
    nologin: !1,
    showlogin: !1,
    is_showloading: !0,
    is_liked: !1,
    is_favored: !1,
    is_downloaded: !1,
    is_related: !1,
    is_preview: !1,
    isDetail: !0,
    isShare: !1,
    prefix: "",
    hiddenName: !0,
    hiddenNames: !1,
    page: 1,
    navH: 0,
    detail: "",
    needcount: app.globalData.downloadPoint,
    bannerAd: adList().bannerAd

  },

  onLoad: function (e) {
    console.log("aa",e)
    this.createAdView();
    var that = this
    that.setData({
      imageUrl: e.picPath,
      picId: e.picId,
      userInfo: app.globalData.userInfo,
    });
    this.navHeight()
  },

  createAdView: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    var that = this;
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: adList().tanchuangAd
      })
      interstitialAd.onLoad(() => {console.log('插屏 广告加载成功')})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
    //创建广告
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: adList().videoAd
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {
        wx.showToast({
          title: '广告加载失败，稍后来试哦~',
          icon: 'none'
        })
      })
      videoAd.onClose((res) => {
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励

          that.addUserPoint(app.globalData.plusPoint, app.globalData.adAddPoint, "视频广告激励积分")
        } else {
          // 播放中途退出，不下发游戏奖励
          wx.showToast({
            title: '看完才能获得奖励哦~',
            icon: 'error'
          })
        }
      })
    }
  },

  addUserPoint: function (type, point, pointDesc) {
    var params = {
      point: point,
      type: type,
      pointDesc: pointDesc
    }
    requst_post_addPoint(params).then(res => {
      if (type == app.globalData.plusPoint) {
        let point1 = app.globalData.userInfo.availablePoint + point;
        app.globalData.userInfo.availablePoint = point1
      } else {
        let point2 = app.globalData.userInfo.availablePoint - point;
        app.globalData.userInfo.availablePoint = point2
      }

    }).catch(err => {

    })
  },

  navHeight: function () {
    var t = this;
    wx.getSystemInfo({
      success: function (e) {
        t.data.navH = e.statusBarHeight + 44, t.setData({
          navH: e.statusBarHeight + 44
        });
      },
      fail: function (t) {
        console.log(t);
      }
    });
  },
  /**
   * 点赞喜欢
   */
  likePic: function () {
    var that = this;
    var params = {
      picId: that.data.picId,
      picPath:that.data.imageUrl
    }
    requst_post_likePic(params).then(res => {
      that.setData({
        isLike: that.data.isLike == 1 ? 0 : 1
      })
      if (that.data.isLike == 1) {
        wx.showToast({
          title: '点赞成功',
        })
      } else {
        wx.showToast({
          title: '取消点赞',
        })
      }
    })
  },

  showAd() {
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
            wx.showToast({
              title: '广告加载失败，稍后来试哦~',
              icon: 'none'
            })
          })
      })
    }
  },

  showmode: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        is_credit: !0,
      })
    } else {
      app.loginWx();
    }
  },
  downloadPicSuccess: function () {
    this.addUserPoint(app.globalData.subtractPoint, app.globalData.downloadPoint, this.data.picId)

  },
  downloadSuccess: function () {
    var that = this;
    if (app.globalData.userInfo.availablePoint >= app.globalData.downloadPoint) {
      that.downloadImgAll();
    } else {
      wx.showToast({
        title: "积分不足，请看完广告获取积分",
        icon: 'none',
        duration: 2000
      })
      that.showAd();
    }
    that.setData({
      showAdOk: 1
    })
  },


  downloadImg: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("授权数据", res)
        if (res.authSetting['scope.writePhotosAlbum']) {
          console.log("授权成功")
          that.setData({
            showAdOk: 1 //显示广告
          })
          that.downloadSuccess();
        } else {
          console.log("未授权")
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log("授权成功1")
              that.setData({
                showAdOk: 2 //显示广告
              })
              that.downloadSuccess();
            },
            fail() {
              wx.showModal({
                content: '检测到您没打开相册授权，是否去设置打开？',
                confirmText: "确认",
                cancelText: "取消",
                success: function (res) {
                  //点击“确认”时打开设置页面
                  if (res.confirm) {
                    console.log('用户点击确认')
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                          that.setData({
                            showAdOk: 2 //显示广告
                          })
                          that.downloadSuccess();
                        } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                          wx.showToast({
                            title: '获取权限失败,请确认相册权限是否开启',
                            icon: 'none'
                          })
                        }
                      }
                    })
                  } else {
                    console.log('用户点击取消')
                    wx.showToast({
                      title: '获取权限失败,请确认相册权限是否开启',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          })
        }
      }
    })




  },

  downloadImgAll: function () {
    var that = this;
    wx.downloadFile({
      url: that.data.imageUrl,
      success: function (t) {
        wx.saveImageToPhotosAlbum({
          filePath: t.tempFilePath,
          success: function (t) {
            that.downloadPicSuccess();
            that.setData({
              is_downloaded: !0,
            })
          },
          fail: function (t) {


          }
        });
      }
    })
  },
  onReady: function () {},
  onShow: function () {
    setTimeout(()=>
    {
     // 在适合的场景显示插屏广告
    var a = Math.ceil(Math.random() * 10);
    console.log(a)
    if (a <= 8) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })}
    }, 2000)
    
    },
  onHide: function () {},
  onUnload: function () {},


  onShareAppMessage: function () {
    return {
      title: "咚，好友发给你一张壁纸、请查收！",
      path: "/pages/detail/detail?picId=" + this.data.picId + "&picPath=" + this.data.imageUrl,
      imageUrl: this.data.imageUrl
    };
  },
  onShareTimeline: function () {
    return {
      title: "咚，好友分享你一张壁纸、请查收！",
      path: "/pages/detail/detail?picId=" + this.data.picId + "&picPath=" + this.data.imageUrl,
      imageUrl: this.data.imageUrl
    };
  },

  bindHome: function () {
    wx.reLaunch({
      url: "/pages/wallpaper/index"
    });
  },

  bindBack: function () {
    wx.navigateBack();
  },
});